 ;(function(){
  'use strict';
  angular.module('controllers.faultLocation.failureLocation')
    .controller('failureModelCtrl',failureModelCtrl);

  function failureModelCtrl($scope,System,COREDATA,FailureModelServer,CoreService,CoreServer,CoreLoading,$mdDialog){
    var queryedSystem = {};
    $scope.toggle = true;
    $scope.failureModel = {};
    $scope.show = {};
    $scope.param = {};
    
    $scope.selector = {
      provinceCode:COREDATA.PROVINCES,
      systemCode:System,
      businessCode:[],
      timeTypes:[{timeTypeName:'天',timeTypeCode:'1'},{timeTypeName:'月',timeTypeCode:'3'}]
    };
    $scope.$watch('failureModel.systemCode',function(n,o){
      if(n === o) { 
        return; 
      } 
      $scope.failureModel.businessCode = undefined;
    },true);

    $scope.getBusinesses = function(systemCode){
      if(!systemCode){
        $scope.failureModel.systemCode = $scope.selector.systemCode[0];
        systemCode = $scope.failureModel.systemCode;
      }
      return CoreServer.getSysBusiness({systemCode:systemCode.systemCode},function(res){
        if(res.state === '10000'){
          $scope.selector.businessCode = res.data;
          queryedSystem = systemCode;
        }
      });
    };

    $scope.resetParam = function(){
      $scope.failureModel = {};
    };
    
    $scope.getFailureModel = getFailureModel;

    function getFailureModel(needQuery){
      var param = {};
      if($scope.toggle||needQuery){
        param = getParams();
        CoreLoading.setState(true);
        FailureModelServer.failureModelQuery(param,function(res){
          if(res.state === '10000' && res.data.viewData.length >= 1){
            angular.copy($scope.failureModel,$scope.param);
            $scope.totalCount = res.data.viewData.length;
            $scope.param.page = {};
            $scope.getBusinesses($scope.failureModel.systemCode).then(function(){
              $scope.$broadcast('toViewModel',res.data.viewData,param,$scope.selector);
              CoreLoading.setState(false);
              $scope.toggle = false;
              $scope.isQuery = true;
            }); 
          }else{
            CoreLoading.setState(false);
            CoreService.dialog(res.state);
          }
        });
      }else{
        $scope.toggle = !$scope.toggle;
      }
    }
    
    $scope.modelAddition = function($event){
      $mdDialog.show({
        controller:modelAddtionCtrl($scope.selector),
        targetEvent:$event,
        templateUrl:'views/faultLocation/failureLocation/modelAddition.html'
      });
    };
    
    function getParams(){
      var param = {};
      if($scope.failureModel.systemCode){
        param.systemName = $scope.failureModel.systemCode.systemName;
      }else{
        angular.forEach(System,function(item){
          if(item.systemName === '统一支付'){
            param.systemName = item.systemName;
          }
        });
      }
      if($scope.failureModel.provinceCode){
        param.provinceName = $scope.failureModel.provinceCode.provinceName;
      }else{
        param.provinceName = '全部';
      }
      if($scope.failureModel.timeType){
        param.timeGra = $scope.failureModel.timeType.timeTypeCode;
      }else{
        param.timeGra = '1';
      }
      if($scope.failureModel.businessCode){
        param.businessName = $scope.failureModel.businessCode.businessName;
      }else{
        param.businessName = '全部';
      }
     
      return param;
    }

    function modelAddtionCtrl(selector,model,param,isUpdate){
      return function($scope,CoreServer,FailureModelServer,CoreService,$timeout){
        var queryedSystem = '';
        $scope.addition = param? param:{};
        $scope.selector = selector;
        $scope.$watch('addition.systemCode',function(n,o){
          if(n === o) {
            return;
          }
          $scope.addition.businessCode = undefined;
        });
        $scope.getBusinesses = function(systemCode){
          if(!systemCode){
            $scope.addition.systemCode = $scope.selector.systemCode[0];
            systemCode = $scope.addition.systemCode;
          }
          if(queryedSystem === systemCode){
            return;
          }
          return CoreServer.getSysBusiness({systemCode:systemCode.systemCode},function(res){
            if(res.state === '10000'){
              $scope.selector.businessCode = res.data;
              queryedSystem = systemCode;
            }
          });
        };

        function setParam(param){
          if($scope.addition.systemCode){
            param.systemName = $scope.addition.systemCode.systemName;
          }else{
            param.systemName = $scope.selector.systemCode[0].systemName;
          }

          if($scope.addition.businessCode){
            param.businessName = $scope.addition.businessCode.businessName;
          }

          if($scope.addition.provinceCode){
            param.provinceName = $scope.addition.provinceCode.provinceName;
          }else{
            param.provinceName = '广东';
          }

          if($scope.addition.timeType){
            param.timeGra = $scope.addition.timeType.timeTypeCode;
          }else{
            param.timeGra = '1';
          }
          param.model = [];
          for(var i = 0;i < 24;i++){
            param.model.push({
              avg:0,
              warningMax:0,
              warningMin:0,
              time:''
            });
          }
        }

        $scope.confirm = function(){
          var param = {};
          setParam(param);
          angular.forEach($scope.model,function(item,key){
            angular.forEach(item.data,function(subItem,subKey){
              param.model[subKey][key] = Number(subItem.value);
              param.model[subKey].time = subKey+':00';
            });
          });
          if(!isUpdate){
            FailureModelServer.buildAddtion(param,function(res){
              if(res.state !== '10000'){
                $timeout(function(){                 
                  CoreService.dialog(res.state);
                },0);
              }else{
                $timeout(function(){
                  getFailureModel(true);
                  CoreService.dialog('新建成功');
                },0);
              }
            });
          }else{
            FailureModelServer.modifyBuild(param,function(res){
              if(res.state !== '10000'){
                $timeout(function(){
                  CoreService.dialog(res.state);
                },0);
              }else{
                $timeout(function(){
                  getFailureModel(true);
                  CoreService.dialog('修改成功');
                },0);
              }
            });
           
          }
        };

        $scope.cancel = function(){
          $mdDialog.hide();
        };
        $scope.time = [];
        for(var i = 0;i <24;i++){
          $scope.time.push(i+':00');
        }

        if(model){
          $scope.model = model;
        }else{
          $scope.model = {
            'warningMax':{name:'最大值',data:[]},
            'warningMin':{name:'最小值',data:[]},
            'avg':{name:'平均值',data:[]}
          };    
          angular.forEach($scope.model,function(item){
            for(var i = 0; i < 24;i++){
              item.data.push({value:''});
            }
          });
        }
      };
    }
  }

  failureModelCtrl.$inject = ['$scope','System','COREDATA','FailureModelServer','CoreService','CoreServer','CoreLoading','$mdDialog'];
})();

;(function(){
  angular.module('controllers.faultLocation.failureLocation')
    .controller('failureModelViewCtrl',failureModelViewCtrl);

  function failureModelViewCtrl($scope,FailureModelServer,$mdDialog,CoreServer,$timeout,CoreService,CoreLoading){
    var failureModelChart = echarts.init(document.getElementById('failureModelChart'));
    var selector = {};
    var selectedModels = []; 
    var pageParam = {};
    $scope.$on('toViewModel',function(d,data,param,pselector){
      $scope.param.page = {
        pageSize:'10',currentPage:1
      };
      $scope.page = {pageSize:'10',currentPage:1};
      $scope.models = [];
      setSeries(data,1,10);
      $scope.show.table = false;
      $scope.show.chart = false;
      $scope.allCheck = false;
      pageParam = param;
      selectedModels = []; 
      selector = pselector;
    });

    $scope.turnToPage = function(){
      var tempParam = {};
      angular.copy(pageParam,tempParam);
      delete tempParam.page;
      FailureModelServer.failureModelQuery(tempParam,function(res){
        if(res.state !== '10000' && res.data.viewData.length === 0){
          CoreService.dialog(res.state);
          return;
        }
        setSeries(res.data.viewData,$scope.param.page.currentPage,$scope.param.page.pageSize);
      });
    };

    $scope.pageSizeChange = function(size){
      $scope.param.page.pageSize = size;
    }

    function setSeries(data,currentPage,pageSize){
      var begin = Number(currentPage-1)*Number(pageSize),
          end = Number(currentPage)*Number(pageSize);
      $scope.models = [];
      $scope.totalCount = data.length;
      for(;begin < data.length && begin <= end;begin++){
        $scope.models.push(data[begin]);
      }
    }

    $scope.singletonModel = function(model){
      var param = {
        systemName:model.systemName,
        provinceName:model.provinceName,
        businessName:model.businessName
      };
      CoreLoading.setState(true);
      FailureModelServer.singletonModel(param,function(res){
        if(res.state !== '10000' || is.not.array(res.data) || res.data.length === 0){
          CoreLoading.setState(false);
          CoreService.dialog('10003');
          return;
        }
        $scope.series = res.data;
        setModelChart(res.data);
        CoreLoading.setState(false);
        $scope.show.table = true;
        $scope.show.chart = false;
      });
    };

    $scope.changeShowType = function(type){
      $scope.show.chart = false;
      $scope.show.table = false;
      $scope.show[type] = true;
    };
    
    $scope.pickAll = function(){
      $timeout(function(){
        if($scope.allCheck && selectedModels.length !== $scope.models.length){
          selectedModels = [];
          angular.forEach($scope.models,function(item){
            item.checked = true;
            selectedModels.push(item);
            item.index = selectedModels.length-1;
          });
        }else{
          selectedModels = [];
          angular.forEach($scope.models,function(item){
            item.checked = false;
            item.index = undefined;
          });
        }
      },0);
    };

    $scope.pickModel = function(item){
      if(selectedModels[item.index]){
        selectedModels.splice(item.index,1);
        for(var i = item.index;i<selectedModels.length;i++){
          selectedModels[i].index = selectedModels[i].index-1;
        }
        item.index = undefined;
      }else{
        selectedModels.push(item);
        item.index = selectedModels.length-1;
      }
      if(selectedModels.length === $scope.models.length){
        $scope.allCheck = true;
      }else{
        $scope.allCheck = false;
      }
    };
    $scope.deleteBuild = function($event){
      if(selectedModels.length === 0){
        return;
      }
      var confirm = $mdDialog.confirm()
        .title('警告')
        .content('是否删除已选中模型')
        .cancel('取消')
        .ok('确认')
        .targetEvent($event);
      $mdDialog.show(confirm).then(sureToDelete);

      function sureToDelete() {
        var param = [];
        angular.forEach($scope.models,function(item){
          if(!item.checked){
            param.push({
              businessName:item.businessName,
              systemName:item.systemName,
              provinceName:item.provinceName
            });
          }
        });
        FailureModelServer.deleteBuild(param,function(res){
          if(res.state === '10000'){
            $timeout(function(){
              CoreService.dialog('删除成功');
              $scope.getFailureModel(true);
            },0);
          }else{
            $timeout(function(){
              CoreService.dialog(res.state);
            },0);
          }
        });
        
      }
    };

    $scope.modelUpdate = function($event){
      if(selectedModels.length !== 1){
        CoreService.dialog('请选择单项预警模型进行修改');
        return;
      }
      var param = {};
      var tempParam = {
        provinceName:selectedModels[0].provinceName,
        systemName:selectedModels[0].systemName,
        businessName:selectedModels[0].businessName
      };
      CoreLoading.setState(true);
      FailureModelServer.singletonModel(tempParam,function(res){
        var model = {
          'warningMax':{name:'最大值',data:[]},
          'warningMin':{name:'最小值',data:[]},
          'avg':{name:'平均值',data:[]}
        };
        if(res.state !== '10000' || is.not.array(res.data) || res.data.length === 0){
          CoreLoading.setState(false);
          CoreService.dialog('10003');
          return;
        }
        angular.forEach($scope.selector.provinceCode,function(item){
          if(item.provinceName === tempParam.provinceName){
            param.provinceCode = item;
          }
        });
        angular.forEach($scope.selector.businessCode,function(item){
          if(item.businessName === tempParam.businessName){
            param.businessCode = item;
          }
        });
        angular.forEach($scope.selector.systemCode,function(item){
          if(item.systemName === tempParam.systemName){
            param.systemCode = item;
          }
        });
        param.timeType = $scope.selector.timeTypes[0];
        angular.forEach(res.data,function(item){
          model.warningMax.data.push({value:item.warningMax});
          model.warningMin.data.push({value:item.warningMin});
          model.avg.data.push({value:item.avg});
        });
        CoreLoading.setState(false);
        $mdDialog.show({
          controller:modelAddtionCtrl($scope.getFailureModel,selector,model,param,true),
          targetEvent:$event,
          templateUrl:'views/faultLocation/failureLocation/modelAddition.html'
        });
      });
    };
    
    function setModelChart(data){
      var opt = {};
      var seriesData = {
        '0':[],'1':[],'2':[],'3':[],'4':[]
      };
      var x;
      var xAxis = [];
      var title = '';
      angular.forEach(data,function(item,key){
        // seriesData[0].push(item.maxFault);
        // seriesData[1].push(item.minFault);
        seriesData[2].push(item.warningMax);
        seriesData[3].push(item.warningMin);
        seriesData[4].push(item.avg);
        x = key+':00';
        xAxis.push(x);
      });
      opt = new ChartOpt(title,seriesData,xAxis);
      
      failureModelChart.clear();
      failureModelChart.setOption(opt);
    }


    function ChartOpt(title,seriesData,xAxis){
      this.title = {
        text:title,
        x:'center'
      };
      this.xAxis = [
        {
          type:'category',data:xAxis
        }   
      ];
      this.legend = {show:true,orient:'vertical',data:[
        // '故障最大值','故障最小值',
        '预警最大值','预警最小值','平均值'],y:'center',x:'right'};
      this.tooltip = {show:true,trigger:'axis'};
      this.animation = false;
      this.grid = {x2:120};
      this.yAxis = [ 
        {
          type : 'value',splitLine: {show:false},
        }
      ];
      this.series = [
        // {
        //   name:'故障最大值',type:'line',data:seriesData[0],symbolSize:0,clickable:false,itemStyle:{emphasis: {color: 'rgba(0,0,0,0)'}}
        // },
        // {
        //   name:'故障最小值',type:'line',data:seriesData[1],symbolSize:0,clickable:false,itemStyle:{emphasis: {color: 'rgba(0,0,0,0)'}}
        // },
        {
          name:'预警最大值',type:'line',data:seriesData[2],symbolSize:2,symbol:'circle',clickable:false,itemStyle:{emphasis: {color: 'rgba(0,0,0,0)'}}
        },
        {
          name:'预警最小值',type:'line',data:seriesData[3],symbolSize:2,symbol:'circle',clickable:false,itemStyle:{emphasis: {color: 'rgba(0,0,0,0)'}}
        },
        {
          name:'平均值',type:'line',data:seriesData[4],symbolSize:2,symbol:'circle',clickable:false,itemStyle:{emphasis: {color: 'rgba(0,0,0,0)'}}
        }
      ];
    }

    function modelAddtionCtrl(fn,selector,model,param,isUpdate){
      return function($scope,CoreServer,FailureModelServer,CoreService,$timeout){
        var queryedSystem = '';
        $scope.addition = param? param:{};
        $scope.selector = selector;
        $scope.$watch('addition.systemCode',function(n,o){
          if(n === o){
           return;
          }
          $scope.addition.businessCode = undefined;
        });
        $scope.getBusinesses = function(systemCode){
          if(!systemCode){
            $scope.addition.systemCode = $scope.selector.systemCode[0];
            systemCode = $scope.addition.systemCode;
          }
          // if(queryedSystem === systemCode){
          //   return;
          // }
          return CoreServer.getSysBusiness({systemCode:systemCode.systemCode},function(res){
            if(res.state === '10000'){
              $scope.selector.businessCode = res.data;
              queryedSystem = systemCode;
            }
          });
        };

        function setParam(param){
          if($scope.addition.systemCode){
            param.systemName = $scope.addition.systemCode.systemName;
          }else{
            param.systemName = $scope.selector.systemCode[0].systemName;
          }

          if($scope.addition.businessCode){
            param.businessName = $scope.addition.businessCode.businessName;
          }

          if($scope.addition.provinceCode){
            param.provinceName = $scope.addition.provinceCode.provinceName;
          }else{
            param.provinceName = '广东';
          }

          if($scope.addition.timeType){
            param.timeGra = $scope.addition.timeType.timeTypeCode;
          }else{
            param.timeGra = '1';
          }
          param.model = [];
          for(var i = 0;i < 24;i++){
            param.model.push({
              avg:0,
              warningMax:0,
              warningMin:0,
              time:''
            });
          }
        }

        $scope.confirm = function(){
          var param = {};
          setParam(param);
          angular.forEach($scope.model,function(item,key){
            angular.forEach(item.data,function(subItem,subKey){
              param.model[subKey][key] = Number(subItem.value);
              param.model[subKey].time = subKey+':00';
            });
          });
          if(!isUpdate){
            FailureModelServer.buildAddtion(param,function(res){
              if(res.state !== '10000'){
                $timeout(function(){
                  CoreService.dialog(res.state);
                },0);
              }else{
                $timeout(function(){
                  CoreService.dialog('新建成功');
                  fn(true);
                },0);
              }
            });
          }else{
            FailureModelServer.modifyBuild(param,function(res){
              if(res.state !== '10000'){
                $timeout(function(){
                  CoreService.dialog(res.state);
                },0);
              }else{
                $timeout(function(){
                  CoreService.dialog('修改成功');
                  fn(true);
                },0);
              }
            });
           
          }
        };

        $scope.cancel = function(){
          $mdDialog.hide();
        };
        $scope.time = [];
        for(var i = 0;i <24;i++){
          $scope.time.push(i+':00');
        }

        if(model){
          $scope.model = model;
        }else{
          $scope.model = {
            'warningMax':{name:'最大值',data:[]},
            'warningMin':{name:'最小值',data:[]},
            'avg':{name:'平均值',data:[]}
          };    
          angular.forEach($scope.model,function(item){
            for(var i = 0; i < 24;i++){
              item.data.push({value:''});
            }
          });
        }
      };
    }
  }

  failureModelViewCtrl.$inject = ['$scope','FailureModelServer','$mdDialog','CoreServer','$timeout','CoreService','CoreLoading'];
})();